package com.mall.payment.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.mall.common.page.PageData;
import com.mall.common.utils.TimeUtils;
import com.mall.payment.config.AlipayConfig;
import com.mall.payment.entity.PaymentEntity;
import com.mall.payment.service.PaymentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.Map;

/**
 * @author: 谢君臣
 * @Date: 2022/6/24-11:49
 * @version: 1.0
 * @function:
 */
@Slf4j
@Api(tags = "payController")
@RestController
@RequestMapping("/payment/total")
public class PaymentController {

    private final PaymentService paymentService;

    @Resource
    private AlipayConfig alipayConfig;

    public PaymentController(PaymentService paymentService) {
        this.paymentService = paymentService;
    }

    @PostMapping("/trade/notify")
    @ApiOperation("支付通知接口")
    public String aLiPayNotify(@RequestParam Map<String,String> params){
        try {
            //RSA验签
            log.info(params.toString());
            boolean checkV1 = AlipaySignature.rsaCheckV1(
                    params,
                    alipayConfig.getAlipayPublicKey(),
                    alipayConfig.getCharset(),
                    alipayConfig.getSignType()
            );
            if (!checkV1)
                throw new RuntimeException("验签失败");

            //业务数据验签
            // 单号验证
            String transactionId = params.get("out_trade_no");
            PaymentEntity payment = paymentService.getPaymentByTransactionId(transactionId);
            if (payment==null) {
                throw new RuntimeException("订单不存在");
            }
            // 验证金额 (小数点)
            if (new BigDecimal(params.get("total_amount")).subtract(payment.getPayerTotal()).abs().doubleValue() >= 0.01) {
                throw new RuntimeException("金额校验失败");
            }
            // 验证商户
            if (!params.get("seller_id").equals(alipayConfig.getSellerId())) {
                throw new RuntimeException("商户校验失败");
            }
            // 验证AppId
            if (!params.get("app_id").equals(alipayConfig.getAppId())) {
                throw new RuntimeException("AppId校验失败");
            }
            // 验证AppId
            if (!params.get("trade_status").equals("TRADE_SUCCESS") && !params.get("trade_status").equals("TRADE_FINISHED")) {
                throw new RuntimeException("AppId校验失败");
            }
            String status = "success";
            payment.setStatus(status);
            payment.setTradeNo(params.get("trade_no"));
            payment.setUpdateTime(new Date());
            paymentService.updateStatus(payment);
            return status;
        } catch (AlipayApiException e) {
            e.printStackTrace();
            log.info(e.getMessage());
            return "failure";
        }
    }

    @PostMapping("/get")
    @ApiOperation("123")
    public PageData<PaymentEntity> getAll(@ApiIgnore @RequestParam Map<String, Object> params){
        PageData<PaymentEntity> payments = paymentService.findAll(params);
        return payments;
    }
}
